//
// Created by 24087 on 2025/3/29.
//

#include "../Inc/my_can.h"

const uint32_t _STD_ID = 0x00FF;
const uint32_t _EXT_ID = 0x0000;
const uint32_t _LENGTH = 8;
uint8_t RxData[8];
CAN_RxHeaderTypeDef RxHeader;
uint8_t TxData[8] = {0};
uint32_t MailBox0;

const CAN_FilterTypeDef Filter0_cfg = {
    .FilterBank = 0, /*选择过滤器组0~13*/
    .FilterMode = CAN_FILTERMODE_IDMASK, /*配置为掩码模式*/
    .FilterScale = CAN_FILTERSCALE_32BIT, /*32位模式*/
    .FilterIdHigh = 0x0,
    .FilterIdLow = 0x0,
    .FilterMaskIdHigh = 0x0,
    .FilterMaskIdLow = 0x0,
    .FilterFIFOAssignment = CAN_RX_FIFO0, /*关联FIFO 0*/
    .FilterActivation = CAN_FILTER_ENABLE /*启用过滤器*/
};

CAN_TxHeaderTypeDef Tx_header = {
    .StdId = _STD_ID,
    .ExtId = _EXT_ID,
    .IDE = CAN_ID_STD,
    .RTR = CAN_RTR_DATA,
    .DLC = _LENGTH,
    .TransmitGlobalTime = DISABLE
};

/*CAN初始化函数
 *
 */
void CAN_Init(const CAN_FilterTypeDef Filter_cfg)
{
    HAL_CAN_ActivateNotification(&hcan1, CAN_IT_RX_FIFO0_MSG_PENDING);
    CAN_Filter_Init(Filter_cfg);
    HAL_CAN_Start(&hcan1);
}

/*CAN发送函数
 * @param header: 数据的头
 * @param Data: 数据的内容
 * @param
 */
HAL_StatusTypeDef CAN_Send(const CAN_TxHeaderTypeDef TxHeader, uint8_t Data[], uint32_t Mailbox)
{
    return HAL_CAN_AddTxMessage(&hcan1, &TxHeader, Data, &Mailbox);
}

/*CAN过滤器配置函数
 * @param Filter_cfg: 过滤器头
 */
HAL_StatusTypeDef CAN_Filter_Init(const CAN_FilterTypeDef Filter_cfg)
{
    return HAL_CAN_ConfigFilter(&hcan1, &Filter_cfg);
}

/*FIFO0检测函数*/
uint32_t Get_FIFO_Flag()
{
    return HAL_CAN_GetRxFifoFillLevel(&hcan1, CAN_RX_FIFO0);
}

/*CAN接收函数
 * @param: 接收文件的头
 */
HAL_StatusTypeDef CAN_Receive(CAN_RxHeaderTypeDef RxHeader)
{
    return HAL_CAN_GetRxMessage(&hcan1, CAN_RX_FIFO0, &RxHeader, RxData);
}

/*CAN接收中断回调函数*/
void HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan)
{
    if (Get_FIFO_Flag())
    {
        CAN_Receive(RxHeader);
    }
}




